import { util } from '../common/util';
import vm from '../main';
import { store } from "../store/index.js";
	
export const request = {
  // post方法
  post: function (url, params, callback, needSuccess = true) {
		uni.showLoading({ title: '加载中' });
		uni.request({
			url: store.getters.getDebugSetting.APIPath + url,
			data: params,
			header: { 
				'token': store.getters.getToken,
				'Accept': 'application/json',
				'Content-Type': 'application/json',
				// 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
			},
			method: 'POST',
			success: (res) => {
				uni.hideLoading();
				let {status: status, msg: msg, data: data, ...rest} = res.data;
				if(store.getters.getDebugSetting.display) 
					console.log({status, msg, data, rest});
				if(status != 0){ // 验证服务器端自定义的错误状态
					vm.$UIplugins.message({message: msg, type: 'error'});
					if(status == 404) loginOut(); // 服务器端判断为token过期情况
					if(needSuccess) return;
				}
				callback({status, msg, data, rest});
			},
			fail: (err) => {
				if(store.getters.getDebugSetting.display)
					console.log(`${url} uni.request post err: \n ${JSON.stringify(err)}`);
				if(err && err.response) showError(err.response);
				else if(err && err.errMsg) showError(err.errMsg);
				uni.hideLoading();
			},
		});
  },
  // get方法
  get:function (url, callback, needSuccess = true) {
		uni.showLoading({ title: '加载中' });
		uni.request({
			url: store.getters.getDebugSetting.APIPath + url,
			header: { 
				'token': store.getters.getToken,
				'Accept': 'application/json',
				'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
			},
			method: 'GET',
			success: (res) => {
				uni.hideLoading();
				let {status: status, msg: msg, data: data, ...rest} = res.data;
				if(store.getters.getDebugSetting.display) 
					console.log({status, msg, data, rest});
				if(status != 0){ // 验证服务器端自定义的错误状态
					vm.$UIplugins.message({message: msg, type: 'error'});
					if(status == 404) loginOut(); // 服务器端判断为token过期情况
					if(needSuccess) return;
				}
				callback({status, msg, data, rest});
			},
			fail: (err) => {
				if(store.getters.getDebugSetting.display)
					console.log(`${url} uni.request get err: \n ${JSON.stringify(err)}`);
				if(err && err.response) showError(err.response);
				else if(err && err.errMsg) showError(err.errMsg);
				uni.hideLoading();
			},
		});
  },
	// uploadFile方法
	uploadFile: async function (filePaths, callback, needSuccess = true) {
		for (var i = 0; i < filePaths.length; i++) {
			uni.showLoading({ title: '上传中' });
			const uploadTask = uni.uploadFile({
				url: store.getters.getDebugSetting.APIPath + url,
				filePath: filePaths[i],
				name: 'file',
				header: { 
					'token': store.getters.getToken,
					'Accept': 'application/json',
					'Content-Type': 'multipart/form-data',
				},
				formData: {
					'method': 'file.upload',
					'upfile': filePaths[i]
				},
				success: (res) => {
					uni.hideLoading();
					let {status: status, msg: msg, data: data, ...rest} = res.data;
					if(store.getters.getDebugSetting.display) 
						console.log({status, msg, data, rest});
					if(status != 0){ // 验证服务器端自定义的错误状态
						vm.$UIplugins.message({message: msg, type: 'error'});
						if(status == 404) loginOut(); // 服务器端判断为token过期情况
						if(needSuccess) return;
					}
					callback({status, msg, data, rest});
				},
				fail: (err) => {
					if(store.getters.getDebugSetting.display)
						console.log(`${url} uni.request uploadFile err: \n ${JSON.stringify(err)}`);
					if(err && err.response) showError(err.response);
					else if(err && err.errMsg) showError(err.errMsg);
					else 
					uni.hideLoading();
				},
			});
			/* uploadTask.onProgressUpdate((res) => {
				console.log('上传进度' + res.progress);
				console.log('已经上传的数据长度' + res.totalBytesSent);
				console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
			
				// 测试条件，取消上传任务。
				if (res.progress > 50) {
					uploadTask.abort();
				}
			}); */
		}
	},
  // uploadImage方法(带有压缩选项)
  uploadImage: async function (files, callback, options, needSuccess = true) {
		for (var i = 0; i < files.length; i++) {
			let convertFile = 
				options.compress ? 
				await util.uploadSectionFile(files[i], options) : 
				files[i];
			uni.showLoading({ title: '上传中' });
			const uploadTask = uni.uploadFile({
				url: store.getters.getDebugSetting.APIPath + url,
				/* filePath: tempFilePaths[i],
				fileType: 'image',
				name: 'file', */
				files: convertFile,
				header: { 
					'token': store.getters.getToken,
					'Accept': 'application/json',
					'Content-Type': 'multipart/form-data',
				},
				formData: {
					'method': 'images.upload',
					//'upfile': tempFilePaths[i]
				},
				success: (res) => {
					uni.hideLoading();
					let {status: status, msg: msg, data: data, ...rest} = res.data;
					if(store.getters.getDebugSetting.display) 
						console.log({status, msg, data, rest});
					if(status != 0){ // 验证服务器端自定义的错误状态
						vm.$UIplugins.message({message: msg, type: 'error'});
						if(status == 404) loginOut(); // 服务器端判断为token过期情况
						if(needSuccess) return;
					}
					callback({status, msg, data, rest});
				},
				fail: (err) => {
					if(store.getters.getDebugSetting.display)
						console.log(`${url} uni.request uploadImage err: \n ${JSON.stringify(err)}`);
					if(err && err.response) showError(err.response);
					else if(err && err.errMsg) showError(err.errMsg);
					uni.hideLoading();
				},
			});
			/* uploadTask.onProgressUpdate((res) => {
				console.log('上传进度' + res.progress);
				console.log('已经上传的数据长度' + res.totalBytesSent);
				console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
			
				// 测试条件，取消上传任务。
				if (res.progress > 50) {
					uploadTask.abort();
				}
			}); */
		}
  },
}; 

const loginOut = () => { // 登出系统
	store.commit('updateToken', '');
	store.commit('updateUserInfo', {});
  vm.$Router.replaceAll({
      path: '/pages/login/Login',
      query: {redirect: vm.$Route.fullPath},   //从哪个页面跳转
  })
};

const showError = error => { // http状态码显示错误提示
	let errorMsg = '';
	if(typeof error == 'string') errorMsg = error;
	else
		switch (error.status) {
			case 400:
				errorMsg = '请求参数错误'
				break
			case 401:
				errorMsg = '未授权，请登录'
				break
			case 403:
				errorMsg = '跨域拒绝访问'
				break
			case 404:
				errorMsg = '请求地址出错'
				break
			case 408:
				errorMsg = '请求超时'
				break
			case 500:
				errorMsg = '服务器内部错误'
				break
			case 501:
				errorMsg = '服务未实现'
				break
			case 502:
				errorMsg = '网关错误'
				break
			case 503:
				errorMsg = '服务不可用'
				break
			case 504:
				errorMsg = '网关超时'
				break
			case 505:
				errorMsg = 'HTTP版本不受支持'
				break
			default:
				errorMsg = error.msg
				break
		};
  vm.$UIplugins.message({message: errorMsg, type: 'error'});
};
	
// 导出api方法对象
export const api = {};
// 获取当前文件夹下的js文件列表并赋值api对象
const files = require.context('.', false, /\.js$/);
files.keys().forEach(key => {
  if(key.indexOf('index') < 0){
    api[key.replace('./', '').replace('_api.js', '')] = files(key).default;
  }
});